package com.walsai.pcsys.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.walsai.pcsys.core.model.User;
import com.walsai.pcsys.core.service.UserManager;

public class LoginController extends SimpleFormController {

	private UserManager userManager;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		User anonymous = (User) command;
		try {
			User temp = this.userManager.get(anonymous.getUsername());
			if (anonymous.getUsername().equals(temp.getUsername())
					&& anonymous.getPassword().equals(temp.getPassword())) {
				HttpSession session = request.getSession();
				session.setAttribute("userInfo", temp);
				return new ModelAndView(this.getSuccessView());
			} else {
				return new ModelAndView("failed");
			}
		} catch (Exception e) {
			return new ModelAndView("failed");
		}
	}
}
